<?php
/**
 * 图片处理类
 */
class ImageValidate
{
	public function __construct()
	{
		//将生成的验证码写入session，备验证页面使用
		session_start();
	}
	
	public function show()
	{
	    //随机生成一个4位数的数字验证码
	    $num = $this->getRandCode(4);
	    $_SESSION["VALIDATEIMAGE_CODE"] = $num;
	   //创建图片，定义颜色值
	    header("Content-type: image/PNG");
	    srand((double)microtime()*1000000);
	    $im = imagecreate(60,25);
	    $black = ImageColorAllocate($im, 0,128,0);
	    $gray = ImageColorAllocate($im, 225,255,196);
	    imagefill($im,0,0,$gray);
	
	    //随机绘制两条虚线，起干扰作用
	    $style = array($black, $black, $black, $black, $black, $gray, $gray, $gray, $gray, $gray);
	    imagesetstyle($im, $style);
	    $y1=rand(0,20);
	    $y2=rand(0,20);
	    $y3=rand(0,20);
	    $y4=rand(0,20);
	    imageline($im, 0, $y1, 60, $y3, IMG_COLOR_STYLED);
	    imageline($im, 0, $y2, 60, $y4, IMG_COLOR_STYLED);
	
	    //在画布上随机生成大量黑点，起干扰作用;
	    for($i = 0; $i < 30; $i++)
	    {
	    	imagesetpixel($im, rand(0,60), rand(0,20), $black);
	    }
	    //将四个数字随机显示在画布上,字符的水平间距和位置都按一定波动范围随机生成
	    $strx = rand(3,8);
	    for($i=0; $i<4; $i++)
	    {
		    $strpos=rand(1,6);
		    imagestring($im,12,$strx,$strpos, substr($num,$i,1), $black);
		    $strx += rand(8,12);
	    }
	    ImagePNG($im);
	    ImageDestroy($im);
	}
	
	//检测验证码是否正确
	public function check($code)
	{
		return ( $_SESSION["IMAGEVALIDATE_CODE"] == strtoupper($code) ) ? true : false;
	}
	
	private function getRandCode($n)
	{
		$chars = "ABCDEFGHIJKLMNPQRTUVWXYZ0123456789";
		$len = strlen($chars) - 1;
		for($i = 0; $i < $n; $i++) $s .= $chars[mt_rand(0,$len)];
		return $s;
	}
}
?>
